from pydantic_settings import BaseSettings
from pydantic import AnyHttpUrl
from typing import List, Optional
import logging
import argparse
import sys


# 解析命令行参数
def parse_args():
    parser = argparse.ArgumentParser(description="多租户系统管理后端服务")
    parser.add_argument(
        "--log-level", 
        type=str, 
        choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
        help="设置日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL)"
    )
    parser.add_argument(
        "--log-file", 
        type=str, 
        help="日志文件路径，不设置则输出到控制台"
    )
    
    # 如果没有命令行参数，返回None，避免在导入配置时退出程序
    if len(sys.argv) > 1:
        return parser.parse_args()
    return None


# 解析命令行参数
args = parse_args()


class Settings(BaseSettings):
    PROJECT_NAME: str = "Python 应用模板"
    API_V1_STR: str = "/api/v1"
    SECRET_KEY: str = "jc-multi-tenant-system-manager-1234567890"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    REFRESH_TOKEN_EXPIRE_DAYS: int = 7
    BACKEND_CORS_ORIGINS: List[str] = ["*"]
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: Optional[str] = None
    
    # 数据库配置
    SQLITE_DB_PATH: str = "sqlite+aiosqlite:///../data/app.db"
    MYSQL_SERVER: str = ""
    MYSQL_USER: str = ""
    MYSQL_PASSWORD: str = ""
    MYSQL_DB: str = ""
    DATABASE_URL: Optional[str] = SQLITE_DB_PATH

    class Config:
        case_sensitive = True
        env_file = ".env"


# 创建设置实例
settings = Settings()

# 如果命令行参数存在，覆盖默认配置
if args:
    if args.log_level:
        settings.LOG_LEVEL = args.log_level
    if args.log_file:
        settings.LOG_FILE = args.log_file